<template>
  <div class="ticket-purchase">
    <div class="header">
      <h2>购票系统</h2>
    </div>

    <!-- 车次搜索区域 -->
    <div class="search-section">
      <el-card>
        <template #header>
          <span>车次查询</span>
        </template>
        
        <el-form :model="searchForm" inline>
          <el-form-item label="出发站">
            <el-select v-model="searchForm.startStationId" placeholder="请选择出发站" clearable filterable>
              <el-option
                v-for="station in stations"
                :key="station.id"
                :label="station.stationName"
                :value="station.id"
              />
            </el-select>
          </el-form-item>
          
          <el-form-item label="到达站">
            <el-select v-model="searchForm.endStationId" placeholder="请选择到达站" clearable filterable>
              <el-option
                v-for="station in stations"
                :key="station.id"
                :label="station.stationName"
                :value="station.id"
              />
            </el-select>
          </el-form-item>
          
          <el-form-item label="出行日期">
            <el-date-picker
              v-model="searchForm.travelDate"
              type="date"
              placeholder="请选择出行日期"
              value-format="YYYY-MM-DD"
              :disabled-date="disabledDate"
            />
          </el-form-item>
          
          <el-form-item>
            <el-button type="primary" @click="searchTrains">查询直达车次</el-button>
            <el-button type="success" @click="searchTransferRoutes">查询换乘路线</el-button>
          </el-form-item>
        </el-form>
      </el-card>
    </div>

    <!-- 直达车次列表 -->
    <div class="train-list" v-if="trains.length > 0">
      <el-card>
        <template #header>
          <span>直达车次</span>
        </template>
        
        <el-table :data="trains" border>
          <el-table-column prop="trainNumber" label="车次" width="100" />
          <el-table-column label="出发站-到达站" width="200">
            <template #default="{ row }">
              {{ row.startStationName }} → {{ row.endStationName }}
            </template>
          </el-table-column>
          <el-table-column label="出发时间" width="100">
            <template #default="{ row }">
              {{ row.departureTime }}
            </template>
          </el-table-column>
          <el-table-column label="到达时间" width="100">
            <template #default="{ row }">
              {{ row.arrivalTime }}
            </template>
          </el-table-column>
          <el-table-column label="出行日期" width="120">
            <template #default="{ row }">
              {{ row.travelDate }}
            </template>
          </el-table-column>
          <el-table-column label="操作" width="120">
            <template #default="{ row }">
              <el-button size="small" type="primary" @click="selectTrain(row)">
                选择座位
              </el-button>
            </template>
          </el-table-column>
        </el-table>
      </el-card>
    </div>

    <!-- 换乘路线列表 -->
    <div class="transfer-list" v-if="transferRoutes.length > 0">
      <el-card>
        <template #header>
          <span>换乘路线 (共{{ transferRoutes.length }}个方案)</span>
        </template>
        
        <div class="transfer-routes">
          <div 
            v-for="(route, index) in transferRoutes" 
            :key="index"
            class="transfer-route-card"
          >
            <el-card shadow="hover">
              <div class="route-header">
                <el-tag type="info" size="small">方案 {{ index + 1 }}</el-tag>
                <el-tag type="warning" size="small">总耗时: {{ formatDuration(route.totalDuration) }}</el-tag>
                <el-tag type="success" size="small">总价格: ¥{{ route.totalPrice.toFixed(2) }}</el-tag>
              </div>
              
              <div class="route-details">
                <!-- 第一段行程 -->
                <div class="train-segment">
                  <div class="segment-header">
                    <el-tag size="small">{{ route.firstTrain.trainNumber }}</el-tag>
                    <span class="segment-title">第一段</span>
                  </div>
                  <div class="segment-info">
                    <span>{{ route.firstTrain.startStationName }}</span>
                    <el-icon><Right /></el-icon>
                    <span>{{ route.firstTrain.endStationName }}</span>
                    <span class="time-info">
                      {{ route.firstTrain.departureTime }} → {{ route.firstTrain.arrivalTime }}
                    </span>
                  </div>
                </div>

                <!-- 换乘信息 -->
                <div class="transfer-info">
                  <el-divider content-position="center">
                    <el-tag type="warning" size="small">
                      {{ route.transferStationName }}中转 · 等待{{ route.transferWaitTime }}
                    </el-tag>
                  </el-divider>
                </div>

                <!-- 第二段行程 -->
                <div class="train-segment">
                  <div class="segment-header">
                    <el-tag size="small">{{ route.secondTrain.trainNumber }}</el-tag>
                    <span class="segment-title">第二段</span>
                  </div>
                  <div class="segment-info">
                    <span>{{ route.secondTrain.startStationName }}</span>
                    <el-icon><Right /></el-icon>
                    <span>{{ route.secondTrain.endStationName }}</span>
                    <span class="time-info">
                      {{ route.secondTrain.departureTime }} → {{ route.secondTrain.arrivalTime }}
                    </span>
                  </div>
                </div>
              </div>
              
              <div class="route-actions">
                <el-button size="small" @click="selectTransferRoute(route)">
                  选择此方案
                </el-button>
              </div>
            </el-card>
          </div>
        </div>
      </el-card>
    </div>

    <!-- 座位选择对话框 -->
    <el-dialog v-model="seatDialogVisible" title="选择座位" width="80%" :close-on-click-modal="false">
      <div v-if="selectedTrain">
        <seat-selector
          :train="selectedTrain"
          :start-station-id="searchForm.startStationId!"
          :end-station-id="searchForm.endStationId!"
          @seat-selected="handleSeatSelected"
        />
      </div>
    </el-dialog>

    <!-- 换乘座位选择对话框 -->
    <el-dialog v-model="transferSeatDialogVisible" title="选择换乘座位" width="90%" :close-on-click-modal="false">
      <div v-if="selectedTransferRoute">
        <transfer-seat-selector
          :transfer-route="selectedTransferRoute"
          :start-station-id="searchForm.startStationId!"
          :end-station-id="searchForm.endStationId!"
          @seat-selected="handleTransferSeatSelected"
        />
      </div>
    </el-dialog>

    <!-- 购票信息填写对话框 -->
    <el-dialog v-model="purchaseDialogVisible" title="填写乘车人信息" width="600px" :close-on-click-modal="false">
      <div class="selected-info" v-if="selectedSeat">
        <el-descriptions title="选择的座位信息" :column="2" border>
          <el-descriptions-item label="车次">{{ selectedTrain?.trainNumber }}</el-descriptions-item>
          <el-descriptions-item label="座位">{{ selectedSeat.carriageNumber }}车厢{{ selectedSeat.seatNumber }}座</el-descriptions-item>
          <el-descriptions-item label="出发站">{{ getStationName(searchForm.startStationId!) }}</el-descriptions-item>
          <el-descriptions-item label="到达站">{{ getStationName(searchForm.endStationId!) }}</el-descriptions-item>
          <el-descriptions-item label="价格">¥{{ selectedSeat.price }}</el-descriptions-item>
          <el-descriptions-item label="出行日期">{{ searchForm.travelDate }}</el-descriptions-item>
        </el-descriptions>
      </div>

      <el-form :model="passengerForm" :rules="passengerRules" ref="passengerFormRef" label-width="100px" class="passenger-form">
        <el-form-item label="姓名" prop="passengerName">
          <el-input v-model="passengerForm.passengerName" placeholder="请输入乘车人姓名" />
        </el-form-item>
        <el-form-item label="身份证号" prop="passengerIdCard">
          <el-input v-model="passengerForm.passengerIdCard" placeholder="请输入身份证号" />
        </el-form-item>
      </el-form>

      <template #footer>
        <span class="dialog-footer">
          <el-button @click="purchaseDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="purchaseTicket" :loading="purchasing">
            确认购票
          </el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { trainApi, stationApi, ticketApi } from '@/api/train'
import { useUserStore } from '@/stores/user'
import type { Train, Station, Seat, TicketInfo, TransferRoute, TransferTicketInfo } from '@/types/train'
import SeatSelector from './components/SeatSelector.vue'
import TransferSeatSelector from './components/TransferSeatSelector.vue'
import { Right } from '@element-plus/icons-vue'

const userStore = useUserStore()

const trains = ref<Train[]>([])
const transferRoutes = ref<TransferRoute[]>([])
const stations = ref<Station[]>([])
const selectedTrain = ref<Train | null>(null)
const selectedTransferRoute = ref<TransferRoute | null>(null)
const selectedSeat = ref<Seat | null>(null)
const selectedFirstSeat = ref<Seat | null>(null)
const selectedSecondSeat = ref<Seat | null>(null)
const seatDialogVisible = ref(false)
const transferSeatDialogVisible = ref(false)
const purchaseDialogVisible = ref(false)
const purchasing = ref(false)
const passengerFormRef = ref()

const searchForm = reactive({
  startStationId: null as number | null,
  endStationId: null as number | null,
  travelDate: ''
})

const passengerForm = reactive({
  passengerName: '',
  passengerIdCard: ''
})

const passengerRules = {
  passengerName: [
    { required: true, message: '请输入乘车人姓名', trigger: 'blur' },
    { min: 2, max: 50, message: '姓名长度在2到50个字符', trigger: 'blur' }
  ],
  passengerIdCard: [
    { required: true, message: '请输入身份证号', trigger: 'blur' },
    { pattern: /(^\d{15}$)|(^\d{18}$)|(^\d{17}(\d|X|x)$)/, message: '身份证号格式不正确', trigger: 'blur' }
  ]
}

// 获取车站列表
const fetchStations = async () => {
  try {
    const response = await stationApi.getAllStations()
    if (response.success) {
      stations.value = response.data
    } else {
      ElMessage.error(response.message)
    }
  } catch (error) {
    console.error('获取车站列表失败:', error)
    ElMessage.error('获取车站列表失败')
  }
}

// 搜索车次
const searchTrains = async () => {
  if (!validateSearchForm()) return

  try {
    // 清空换乘路线结果
    transferRoutes.value = []
    
    const response = await trainApi.searchTrains(
      searchForm.startStationId!,
      searchForm.endStationId!,
      searchForm.travelDate
    )
    if (response.success) {
      trains.value = response.data
      if (trains.value.length === 0) {
        ElMessage.info('暂无符合条件的直达车次')
      }
    } else {
      ElMessage.error(response.message)
    }
  } catch (error) {
    console.error('搜索车次失败:', error)
    ElMessage.error('搜索车次失败')
  }
}

// 搜索换乘路线
const searchTransferRoutes = async () => {
  if (!validateSearchForm()) return

  try {
    // 清空直达车次结果
    trains.value = []
    
    const response = await trainApi.searchTransferRoutes(
      searchForm.startStationId!,
      searchForm.endStationId!,
      searchForm.travelDate,
      120 // 默认最大换乘等待时间2小时
    )
    if (response.success) {
      transferRoutes.value = response.data
      if (transferRoutes.value.length === 0) {
        ElMessage.info('暂无符合条件的换乘路线')
      } else {
        ElMessage.success(`找到 ${transferRoutes.value.length} 个换乘方案`)
      }
    } else {
      ElMessage.error(response.message)
    }
  } catch (error) {
    console.error('搜索换乘路线失败:', error)
    ElMessage.error('搜索换乘路线失败')
  }
}

// 验证搜索表单
const validateSearchForm = () => {
  if (!searchForm.startStationId || !searchForm.endStationId || !searchForm.travelDate) {
    ElMessage.warning('请完整填写搜索条件')
    return false
  }
  
  if (searchForm.startStationId === searchForm.endStationId) {
    ElMessage.warning('出发站和到达站不能相同')
    return false
  }

  return true
}

// 选择车次
const selectTrain = (train: Train) => {
  selectedTrain.value = train
  selectedTransferRoute.value = null
  seatDialogVisible.value = true
}

// 选择换乘路线
const selectTransferRoute = (route: TransferRoute) => {
  selectedTransferRoute.value = route
  selectedTrain.value = null
  transferSeatDialogVisible.value = true
}

// 格式化时长显示
const formatDuration = (minutes: number) => {
  const hours = Math.floor(minutes / 60)
  const mins = minutes % 60
  return `${hours}小时${mins}分钟`
}

// 处理换乘座位选择
const handleTransferSeatSelected = (firstSeat: Seat, secondSeat: Seat, passengerInfo: { passengerName: string; passengerIdCard: string }) => {
  selectedFirstSeat.value = firstSeat
  selectedSecondSeat.value = secondSeat
  
  // 预填乘车人信息
  passengerForm.passengerName = passengerInfo.passengerName
  passengerForm.passengerIdCard = passengerInfo.passengerIdCard
  
  transferSeatDialogVisible.value = false
  purchaseTransferTickets(passengerInfo)
}

// 购买换乘票务
const purchaseTransferTickets = async (passengerInfo: { passengerName: string; passengerIdCard: string }) => {
  if (!userStore.isLoggedIn) {
    ElMessage.warning('请先登录')
    return
  }

  if (!selectedTransferRoute.value || !selectedFirstSeat.value || !selectedSecondSeat.value) {
    ElMessage.error('座位选择信息不完整')
    return
  }

  try {
    purchasing.value = true

    const transferTicketInfo: TransferTicketInfo = {
      firstTrainId: selectedTransferRoute.value.firstTrain.id,
      firstSeatId: selectedFirstSeat.value.id,
      secondTrainId: selectedTransferRoute.value.secondTrain.id,
      secondSeatId: selectedSecondSeat.value.id,
      passengerName: passengerInfo.passengerName,
      passengerIdCard: passengerInfo.passengerIdCard,
      startStationId: searchForm.startStationId!,
      transferStationId: selectedTransferRoute.value.transferStationId,
      endStationId: searchForm.endStationId!
    }

    const response = await ticketApi.purchaseTransferTickets({
      userId: userStore.currentUser!.id,
      transferTickets: [transferTicketInfo]
    })

    if (response.success) {
      ElMessage.success('换乘票务购买成功！')
      
      // 显示订单详情
      await ElMessageBox.alert(
        `订单号：${response.data.orderNumber}\n总金额：¥${response.data.totalAmount}\n订单类型：换乘票务`,
        '购票成功',
        { type: 'success' }
      )
      
      // 重置表单
      resetForms()
    } else {
      ElMessage.error(response.message)
    }
  } catch (error) {
    console.error('购买换乘票务失败:', error)
    ElMessage.error('购买换乘票务失败')
  } finally {
    purchasing.value = false
  }
}

// 处理座位选择
const handleSeatSelected = (seat: Seat) => {
  selectedSeat.value = seat
  seatDialogVisible.value = false
  purchaseDialogVisible.value = true
  
  // 如果用户已登录，可以预填乘车人信息
  if (userStore.currentUser) {
    passengerForm.passengerName = userStore.currentUser.realName
    passengerForm.passengerIdCard = userStore.currentUser.idCard
  }
}

// 购票
const purchaseTicket = async () => {
  if (!userStore.isLoggedIn) {
    ElMessage.warning('请先登录')
    return
  }

  try {
    const valid = await passengerFormRef.value.validate()
    if (!valid) return

    purchasing.value = true

    const ticketInfo: TicketInfo = {
      trainId: selectedTrain.value!.id,
      seatId: selectedSeat.value!.id,
      passengerName: passengerForm.passengerName,
      passengerIdCard: passengerForm.passengerIdCard,
      startStationId: searchForm.startStationId!,
      endStationId: searchForm.endStationId!
    }

    const response = await ticketApi.purchaseTickets({
      userId: userStore.currentUser!.id,
      tickets: [ticketInfo]
    })

    if (response.success) {
      ElMessage.success('购票成功！')
      purchaseDialogVisible.value = false
      
      // 显示订单详情
      await ElMessageBox.alert(
        `订单号：${response.data.orderNumber}\n总金额：¥${response.data.totalAmount}`,
        '购票成功',
        { type: 'success' }
      )
      
      // 重置表单
      resetForms()
    } else {
      ElMessage.error(response.message)
    }
  } catch (error) {
    console.error('购票失败:', error)
    ElMessage.error('购票失败')
  } finally {
    purchasing.value = false
  }
}

// 重置表单
const resetForms = () => {
  Object.assign(passengerForm, {
    passengerName: '',
    passengerIdCard: ''
  })
  selectedTrain.value = null
  selectedTransferRoute.value = null
  selectedSeat.value = null
  selectedFirstSeat.value = null
  selectedSecondSeat.value = null
  seatDialogVisible.value = false
  transferSeatDialogVisible.value = false
  purchaseDialogVisible.value = false
}

// 获取车站名称
const getStationName = (stationId: number) => {
  const station = stations.value.find(s => s.id === stationId)
  return station ? station.stationName : ''
}

// 禁用日期（不能选择过去的日期）
const disabledDate = (time: Date) => {
  return time.getTime() < Date.now() - 24 * 60 * 60 * 1000
}

onMounted(() => {
  fetchStations()
})
</script>

<style scoped>
.ticket-purchase {
  padding: 20px;
}

.header {
  margin-bottom: 20px;
}

.header h2 {
  margin: 0;
  color: #303133;
}

.search-section, 
.train-list {
  margin-bottom: 20px;
}

.selected-info {
  margin-bottom: 20px;
}

.passenger-form {
  margin-top: 20px;
}

/* 换乘路线样式 */
.transfer-list {
  margin-bottom: 20px;
}

.transfer-routes {
  display: flex;
  flex-direction: column;
  gap: 16px;
}

.transfer-route-card {
  width: 100%;
}

.route-header {
  display: flex;
  gap: 10px;
  margin-bottom: 15px;
  align-items: center;
}

.route-details {
  margin: 15px 0;
}

.train-segment {
  margin: 10px 0;
}

.segment-header {
  display: flex;
  align-items: center;
  gap: 8px;
  margin-bottom: 8px;
}

.segment-title {
  font-size: 12px;
  color: #909399;
}

.segment-info {
  display: flex;
  align-items: center;
  gap: 8px;
  font-size: 14px;
}

.time-info {
  margin-left: auto;
  color: #606266;
  font-size: 13px;
}

.transfer-info {
  margin: 15px 0;
}

.route-actions {
  display: flex;
  justify-content: flex-end;
  margin-top: 15px;
}

@media (max-width: 768px) {
  .route-header {
    flex-wrap: wrap;
  }
  
  .segment-info {
    flex-wrap: wrap;
    font-size: 13px;
  }
  
  .time-info {
    margin-left: 0;
    flex-basis: 100%;
  }
}
</style>